﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Http.OData;
using System.Web.Http.OData.Query;

namespace ODataPQ.Extensions
{
    /// <summary>
    /// 用于构建查询数据记录的ODataQueryOptions对象的Helper类
    /// -----------------------------------------------------
    /// add by stupidboy 2015-5-14 17:14:16
    /// </summary>
    public class ODataQueryOptionsExtensions
    {
        private const string SkipKey = "$skip";
        private const string OrderByKey = "$orderby";
        private const string MS_QueryNameValuePairsKey = "MS_QueryNameValuePairs";

        /// <summary>
        /// 创建获取满足$filter的总记录查询ODataQueryOptions对象
        /// ----------------------------------------------------
        /// add by stupidboy 2015-5-15 20:10:20
        /// </summary>
        /// <param name="context"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        public static ODataQueryOptions CreateODataQueryCountOptions(ODataQueryContext context, HttpRequestMessage request)
        {
            object ruteKV = null;
            if (request.Properties.TryGetValue(MS_QueryNameValuePairsKey, out ruteKV))
            {
                IEnumerable<KeyValuePair<string, string>> oldKVs = (IEnumerable<KeyValuePair<string, string>>)ruteKV;
                //(IEnumerable<KeyValuePair<string, string>>)ruteKV
                List<KeyValuePair<string, string>> newKVs = new List<KeyValuePair<string, string>>();

                if (oldKVs != null)
                {
                    foreach (KeyValuePair<string, string> kv in oldKVs)
                    {
                        // 取消排序、Skip、只保留OData $filter 以及其它参数。
                        if (!kv.Key.Equals(SkipKey, StringComparison.Ordinal) && !kv.Key.Equals(OrderByKey, StringComparison.Ordinal))
                        {
                            newKVs.Add(new KeyValuePair<string, string>(kv.Key, kv.Value));
                        }
                    }
                }

                request.Properties.Remove(MS_QueryNameValuePairsKey);

                request.Properties.Add(MS_QueryNameValuePairsKey, newKVs.ToArray());
            }
            return new ODataQueryOptions(context, request);
        }
    }
}